package com.codetile.batch.config;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.batch.item.support.ListItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;


@Configuration
@EnableBatchProcessing
public class ListenerDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job listenerJob(){
        return jobBuilderFactory.get("listenerJob")
                .start(listenerStep1())
//                .listener(new JobListener())
                .build();
    }

    @Bean
    public Step listenerStep1(){
        return stepBuilderFactory.get("listenerStep1")
                .<String,String>chunk(2)
                .faultTolerant()
                //监听，可以获取参数
//                .listener(new MyChunkListener())
                .reader(reade())
                .writer(write())
                .build();


    }

    @Bean
    public ItemReader<String> reade(){
        return new ListItemReader<>(Arrays.asList("java","php","c++"));

//        return new MyReader(Arrays.asList("java","php","c++"));

    }

    @Bean
    public ListItemWriter<Object> write(){
        return new ListItemWriter<Object>(){
            @Override
            public void write(List items) throws Exception {
                for (Object item: items) {
                    System.out.println(item);
                }
            }
        };
    }

}
